/*
 * ChatIHMConnected.java
 *
 */
package Chat.System;

import Chat.Donnees.*;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.HashMap;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;

/**
 * Fenêtre ouverte une fois la connexion activée
 *
 * @author Ndanja et Papa Abdou
 * @param ChatGUI
 *
 */
public class ChatIHMConnected extends javax.swing.JFrame {

    private Onglets onglets;
    private HashMap listeOnglets, listeTransferts;
    private ChatGUI gui;
    private ListContacts listeContacts;
    private DefaultListModel liste;
    private String fileSendPath;
    private String filereceivePath;

    /** Creates new form IHM Connected */
    public ChatIHMConnected(ChatGUI gui) {

        int i;
        this.gui = gui;
        listeOnglets = new HashMap();
        liste = new DefaultListModel();
        fileSendPath = new String();
        filereceivePath = new String();
        initComponents();

    }

    /**
     * Permet de récupérer la référence du ChatGUI
     * @return
     */
    public ChatGUI getGUI() {
        return this.gui;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        bSend = new javax.swing.JButton();
        bDisconnect = new javax.swing.JButton();
        scrolljList = new javax.swing.JScrollPane();
        jList = new javax.swing.JList(liste);
        lesOnglets = new javax.swing.JTabbedPane();
        msgEdit = new javax.swing.JTextField();
        bSendFile = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        bSend.setText("Envoyer");
        bSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bSendActionPerformed(evt);
            }
        });
        bSend.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                bSendKeyPressed(evt);
            }
        });

        bDisconnect.setText("Déconnexion");
        bDisconnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bDisconnectActionPerformed(evt);
            }
        });

        jList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jListMouseClicked(evt);
            }
        });
        scrolljList.setViewportView(jList);

        msgEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                msgEditActionPerformed(evt);
            }
        });
        msgEdit.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                msgEditKeyPressed(evt);
            }
        });

        bSendFile.setText("Envoie Fichier");
        bSendFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bSendFileActionPerformed(evt);
            }
        });
        bSendFile.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                bSendFileKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(msgEdit, javax.swing.GroupLayout.DEFAULT_SIZE, 481, Short.MAX_VALUE)
                    .addComponent(lesOnglets, javax.swing.GroupLayout.DEFAULT_SIZE, 481, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(bSend, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(bDisconnect))
                    .addComponent(scrolljList, javax.swing.GroupLayout.DEFAULT_SIZE, 241, Short.MAX_VALUE)
                    .addComponent(bSendFile, javax.swing.GroupLayout.DEFAULT_SIZE, 241, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lesOnglets, javax.swing.GroupLayout.DEFAULT_SIZE, 393, Short.MAX_VALUE)
                        .addGap(14, 14, 14))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(scrolljList, javax.swing.GroupLayout.PREFERRED_SIZE, 352, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bSendFile, javax.swing.GroupLayout.DEFAULT_SIZE, 43, Short.MAX_VALUE)
                        .addGap(6, 6, 6)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(msgEdit, javax.swing.GroupLayout.DEFAULT_SIZE, 43, Short.MAX_VALUE)
                    .addComponent(bSend, javax.swing.GroupLayout.DEFAULT_SIZE, 43, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bDisconnect, javax.swing.GroupLayout.DEFAULT_SIZE, 43, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     *Action Listener du Jlist: Permet de récupérer l'identifiant du contact sélectionnez
     * @param evt
     * 
     */
    private void jListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListMouseClicked
        // TODO add your handling code here:
        actionOnglets((String) jList.getSelectedValue());

    }//GEN-LAST:event_jListMouseClicked

    /**
     *Le bouton de déconnexion
     * @param evt
     */
    private void bDisconnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bDisconnectActionPerformed

        disconnect();

    }//GEN-LAST:event_bDisconnectActionPerformed

    /**
     *Clique sur le bouton d'envoie de message
     * @param evt
     */
    private void bSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bSendActionPerformed

        this.sendMessage();

    }//GEN-LAST:event_bSendActionPerformed

    private void bSendKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_bSendKeyPressed
    }//GEN-LAST:event_bSendKeyPressed

    private void msgEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_msgEditActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_msgEditActionPerformed

    /**
     * Action listener pour la touche entrée.
     */
    private void msgEditKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_msgEditKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            this.sendMessage();
        }
    }//GEN-LAST:event_msgEditKeyPressed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        // TODO add your handling code here:
    }//GEN-LAST:event_formWindowClosed

    /**
     *Action à la fermeture de la fenêtre
     */
    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing

        disconnect();
    }//GEN-LAST:event_formWindowClosing

    /**
     * Clic sur le bouton "Envoie Fichier"
     * @param evt
     */
    private void bSendFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bSendFileActionPerformed
        // TODO add your handling code here:

        actionOnglets("Fichiers");

        JFileChooser chooser = new JFileChooser();
        int returnVal = chooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {

            String fname = chooser.getSelectedFile().getName();
            int i = (int) chooser.getSelectedFile().length();
            this.fileSendPath = chooser.getCurrentDirectory() + File.separator + fname;
            String destName = jList.getSelectedValue().toString();

            gui.sendFile(this.fileSendPath, fname, destName, i);
        }

    }//GEN-LAST:event_bSendFileActionPerformed

    /**
     * Insertion du progressbar pour l'envoie de fichier
     * @param j : La référence du progressbar
     * @param src: le nickname de l'expéditeur
     * @param dest: le nickname du destinataire
     * @param fName: L'arborescence du fichier
     *
     */
    public void addProgressBar(JProgressBar j, String src, String dest, String fName) {
        OngletTFichiers fOnglets = (OngletTFichiers) listeOnglets.get("Fichiers");
        fOnglets.addProgressBar(j, src, dest, fName);

    }

    private void bSendFileKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_bSendFileKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_bSendFileKeyPressed

    /**
     * Fonction appellant sendMessqge du GUI.
     * 
     */
    private void sendMessage() {

        if (!msgEdit.getText().isEmpty()) {

            onglets = (Onglets) lesOnglets.getSelectedComponent();
            String source = onglets.getName();
            gui.sendMsg(source, msgEdit.getText());
            msgEdit.setText("");
            msgEdit.setBackground(Color.WHITE);

        } else {

            msgEdit.setText(null);
            msgEdit.setBackground(Color.red);
        }
    }

    /**
     * Actions sur les onglets: Permet d'associer une action à un onglet donné
     * @param nomOnglets
     */
    private void actionOnglets(String nomOnglets) {

        // int i = lesOnglets.indexOfTab(nomOnglets);


        if (lesOnglets.indexOfTab(nomOnglets) != -1) {

            lesOnglets.setSelectedIndex(lesOnglets.indexOfTab(nomOnglets));

        } else if (nomOnglets.equalsIgnoreCase("Fichiers")) {

            listeOnglets.put(nomOnglets, onglets = new OngletTFichiers("Fichiers"));
            lesOnglets.addTab(onglets.getName(), onglets);
            lesOnglets.setSelectedIndex(lesOnglets.indexOfTab(onglets.getName()));

        } else {

            listeOnglets.put(nomOnglets, onglets = new Onglets(nomOnglets));
            lesOnglets.addTab(onglets.getName(), onglets);
            lesOnglets.setSelectedIndex(lesOnglets.indexOfTab(onglets.getName()));
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bDisconnect;
    private javax.swing.JButton bSend;
    private javax.swing.JButton bSendFile;
    private javax.swing.JList jList;
    private javax.swing.JTabbedPane lesOnglets;
    private javax.swing.JTextField msgEdit;
    private javax.swing.JScrollPane scrolljList;
    // End of variables declaration//GEN-END:variables

    /**
     * Permet de sortir de l'application
     */
    void exit() {
        this.dispose();
    }

    /**
     * Pour se déconnecter et afficher la fenêtre de connexion
     */
    public void disconnect() {
        gui.disconnect();
    }

    /**
     * Fonction permettant d'insérer un nickname dans la liste des utilisateurs
     * @param nickname: nom de l'utilisateur
     */
    void addContact(String nickname) {
        liste.addElement(nickname);
    }

    /**
     * Fonction permettant de supprimer un nom d'utilisateur du JList
     * @param nickname
     */
    public void removeContact(String nickname) {

        liste.removeElement(nickname);
        listeOnglets.get(nickname);
    }

    /**
     * Mise à jour du message dans le bon onglets à la réception d'un nouveau message
     * @param source: nickname de l'expéditeur (peut être l'utilisateur local "MOI ou un utilisateur distant"
     * @param msg: le texte du message envoyé
     */
    public void refreshMsg(String source, String msg) {

        if (source.equals("me")) {

            onglets = (Onglets) lesOnglets.getSelectedComponent();
            onglets.setChatMessage("Moi" + " :\t" + msg + "\n");

        } else {

            actionOnglets(source);
            onglets = (Onglets) lesOnglets.getSelectedComponent();
            onglets.setChatMessage(source + " :\t" + msg + "\n");

        }
    }

    /**
     * Fonction permettant:<br/>
     *          - d'ouvir l'onglets fichier<br/>
     *          - de récupérer l'arborescence d'un fichier reçu<br/>
     * @return: String filereceivePath
     */
    public String refreshFile() {

        actionOnglets("Fichiers");

        int reponse = -1;
        reponse = JOptionPane.showConfirmDialog(this, "Vous avez reçu un nouveau fichier.", "Nouveau fichier", JOptionPane.OK_CANCEL_OPTION);

        if (reponse == JOptionPane.YES_OPTION) {

            JFileChooser chooser = new JFileChooser();
            chooser.setDialogTitle("Choisir le répertoire de stockage");
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int returnVal = chooser.showOpenDialog(this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {

                this.filereceivePath = chooser.getCurrentDirectory().getPath() + File.separator + chooser.getSelectedFile().getName() + File.separator;

            }

        } else {
            this.filereceivePath = "nulle";
        }

        return filereceivePath;
    }
}
